package com;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class LogoutListener implements HttpSessionListener {
	public static final Logger LOG = LoggerFactory.getLogger(LogoutListener.class);

	public LogoutListener() {
	}

	public void sessionCreated(HttpSessionEvent arg0) {
	}

	public void sessionDestroyed(HttpSessionEvent arg0) {

		HttpSession session = arg0.getSession();
		String name = (String) session.getAttribute("nickname");
		ApplicationContext  context = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
		
		LogoutExecutor logoutExecutor = (LogoutExecutor) context.getBean("logoutExecutor");

		try {
			logoutExecutor.logout(name);
		} catch (SQLException | NamingException | IOException e) {
			e.printStackTrace();
		}

		LOG.info("Logged out with name: " + name);
	}

	//
	//
	// Features
	// ---------------------------------------------
	// 1. make nick name unique
	// 2. show all active nick names in chat
	// 3. remove nickname from db. when logged out
	// 4. add to view only 2 minutes
	// ---------------------------------------------
	// Plan
	// ---------------------------------------------
	// 1. Refactoting (abstraction)
	// 1a. Log4j / SLFJ (remove System.out...)
	// 1b. database Connection pool
	// 1c. push to google code SVN
	//
	// 2. Model2: Servlet + JSP
	// ---------------------------------------------
	// 3. JDBC - > Hibernate (ORM)
	// 4. Spring IOC 3.2
	// 5. Servlet/JSP -> Spring 3.2 MVC
	// 6. Spring Security 3.x
	// 7. Jnit Tests
	// 8. Integration Tests
	// 9. Dep. 7, 8 Use Mock frameworks, JBehave / Selenium 2.x
	// 10. Maven2 vs. Ant
	//
}
